﻿using System.Reflection;
using Abp.AspNetCore;
using Abp.AspNetCore.Configuration;
using Abp.Castle.Logging.Log4Net;
using Abp.Configuration.Startup;
using Abp.Domain.Repositories;
using Abp.EntityFrameworkCore;
using Abp.EntityFrameworkCore.Configuration;
using Abp.Modules;
using Abp.Reflection.Extensions;
using AbpAspNetCoreDemo.Core;
using AbpAspNetCoreDemo.Core.Domain;
using AbpAspNetCoreDemoV2.Db;
using Castle.MicroKernel.Registration;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

namespace AbpAspNetCoreDemoV2
{
    [DependsOn(
        typeof(AbpAspNetCoreModule),
        typeof(AbpAspNetCoreDemoCoreModule),
        typeof(AbpEntityFrameworkCoreModule),
        typeof(AbpCastleLog4NetModule)
        )]
    public class AbpAspNetCoreDemoModule : AbpModule
    {
        public override void PreInitialize()
        {
            Configuration.DefaultNameOrConnectionString = IocManager.Resolve<IConfigurationRoot>().GetConnectionString("MySql");

            Configuration.Modules.AbpEfCore().AddDbContext<MyDbContext>(options =>
            {
                if (options.ExistingConnection != null)
                {
                    options.DbContextOptions.UseMySql(options.ExistingConnection);
                }
                else
                {
                    options.DbContextOptions.UseMySql(options.ConnectionString);
                }
            });
            Configuration.ReplaceService<IRepository<Product>>(() =>
            {
                IocManager.IocContainer.Register(
                    Component.For<IRepository<Product>, IProductRepository, ProductRepository>()
                        .ImplementedBy<ProductRepository>()
                        .LifestyleTransient()
                );
            });

            Component.For<IProductRepository, ProductRepository>()
                .ImplementedBy<ProductRepository>()
                .LifestyleTransient();

            Configuration.Modules.AbpAspNetCore()
                .CreateControllersForAppServices(
                    typeof(AbpAspNetCoreDemoCoreModule).GetAssembly()
                );


            Configuration.IocManager.Resolve<IAbpAspNetCoreConfiguration>().RouteConfiguration.Add(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(typeof(AbpAspNetCoreDemoModule).GetAssembly());
        }
    }
}